package services

import (
    "cing.io/cing/internal/conductor"
    "context"
    log "github.com/sirupsen/logrus"
    "io"
    "net/http"

    "github.com/gin-gonic/gin"
    "google.golang.org/protobuf/encoding/protojson"

    "cing.io/cing-api/core"
    "cing.io/cing-api/planner"
    "cing.io/cing/internal/apiserver/common"
    "cing.io/cing/internal/clientcache"
    "cing.io/cing/internal/storage"
    "cing.io/cing/pkg/util"
)

var FeedbackService = &feedbackService{}

type feedbackService struct{}

func (*feedbackService) FeedBack(ctx *gin.Context) {

    feedback := &core.Feedback{}
    bytes, _ := io.ReadAll(ctx.Request.Body)
    err := protojson.Unmarshal(bytes, feedback)
    if err != nil {
        ctx.JSON(http.StatusBadRequest, err)
        return
    }

    log.Debug("feedback: ", feedback)

    tsk := storage.GetTask(util.SplitNamespaceAndName(feedback.TaskFullName))

    plannerCli := clientcache.Planner.GetPlanner(tsk.TaskType)
    if plannerCli == nil {
        ctx.JSON(http.StatusBadRequest, common.TaskTypeNotSupport)
        return
    }

    plan := storage.GetPlan(feedback.TaskFullName, feedback.StartTime.AsTime().UnixMilli())

    // delete
    err = storage.DeletePlan(feedback.TaskFullName, feedback.StartTime.AsTime().UnixMilli())
    if err != nil {
        ctx.JSON(http.StatusBadRequest, err.Error())
        return
    }

    req := &planner.OnSingingEndRequest{
        Task:            tsk,
        ThisPlan:        plan,
        SingerIp:        feedback.SingerIp,
        Successful:      feedback.Successful,
        ActualStartTime: feedback.ActualStartTime,
        ActualEndTime:   feedback.ActualEndTime,
        Feedback:        feedback.Feedback,
    }

    resp, err := plannerCli.OnSingingEnd(context.TODO(), req)

    if resp.NextPlan != nil {
        err := conductor.PutPlan(resp.NextPlan)
        if err != nil {
            ctx.JSON(http.StatusBadRequest, common.CreateTaskError)
            return
        }
    }

    ctx.Status(http.StatusOK)
    return
}
